package com.example.clxy.util;

import com.example.clxy.result.WebRestResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author Hsieh
 * @title: AnnouncementFileUtil
 * @projectName clxy
 * @description:
 * @date 2020/8/1210:47
 */
@Component
public class AnnouncementFileUtil {

    public static String UploadFilePathUrl ;
    public static String FilePathUrl;
    //得到是Windows下的 还是 linux下运行
    public static String system;

    public String getSystem() {
        return system;
    }

    @Value("${run.server.system}")
    public void setSystem(String system) {
        FileUtil.system = system;
    }

    public static String getFilePathUrl() {
        return FilePathUrl;
    }

    @Value("${upload.filePathUrl}")
    public  void setFilePathUrl(String filePathUrl) {
        FilePathUrl = filePathUrl;
    }
    public  String getUploadFilePathUrl() {
        return UploadFilePathUrl;
    }

    @Value("${upload.uploadFilePathUrl}")
    public  void setUploadFilePathUrl(String uploadFilePathUrl) {
        UploadFilePathUrl = uploadFilePathUrl;
    }

    /**
     * 用于校验文件格式,校验文件大小
     * @param file
     * @return
     */
    public static WebRestResult validateFile(MultipartFile file) {
        WebRestResult result = new WebRestResult();
        String fileType = ".pdf,.jpg,.jpeg,.png,.bmp";
        String fileSizeLimit = "104857600";
        if (!file.isEmpty()) {
            try {
                String oldFileName = file.getOriginalFilename();
                if (Tools.isEmpty(oldFileName)) {
                    result.setResult(WebRestResult.FAILURE);
                    result.setMessage("文件格式错误：无文件名！");
                    return result;
                }
                if (!FileUtil.checksSuffix(oldFileName, fileType)) {
                    result.setResult(WebRestResult.FAILURE);
                    result.setMessage("文件格式错误：文件格式错误：非法后缀名！");
                    return result;
                }
                byte[] bytes = new byte[0];
                bytes = file.getBytes();
                if (!FileUtil.checkFileSize(bytes, fileSizeLimit)) {
                    result.setResult(WebRestResult.FAILURE);
                    result.setMessage("文件太大");
                    return result;
                }
            } catch (IOException e) {
                e.printStackTrace();
                result.setMessage("简历文件上传失败," + e.getMessage());
                result.setResult(WebRestResult.FAILURE);
            }
        } else {
            result.setMessage("文件不能为空！");
            result.setResult(WebRestResult.FAILURE);
        }
        result.setResult(WebRestResult.SUCCESS);
        result.setMessage("文件校验成功！");
        return result;
    }

    //获取新文件命名
    public static String getApplyInnovationFileName(String oldFileName) {
        String newFileName = "/userfiles/"  + "/photo/";
        return newFileName;
    }


    //获取新文件命名
    public static String getFileName(String oldFileName, String operationUser ) {
        String datestr = Tools.dateToStr(new Date());
        String suffix = oldFileName.substring(oldFileName.indexOf(".")).toLowerCase();
        String newFileName = "/userfiles/" + operationUser + "/photo/"+ datestr.substring(0, 4) + "/" + datestr.substring(4, 6)+ "/" + UUIDUtil.randomUUID() + suffix;
        return newFileName;
    }

    //保存文件
    public static String writeFile(MultipartFile file, String fileName , String fileUploadLocation)throws IOException{
        //生成上传路径
        String realPath = fileUploadLocation + "/" + fileName;

        File newFile = new File(realPath);

        //判断文件目录是否存在
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }

        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        //保存文件
        file.transferTo(newFile);
        return realPath;
    }

    //删除文件
    public static void delFile(String fileUrl) {
        if(!Tools.isEmpty(fileUrl)){
            File file = new File(fileUrl);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }
    }

    //检查文件后缀
    public static Boolean checksSuffix(String fileName,String fileType){
        if (fileName.indexOf(".") == -1) {
            return false;
        }
        String suffix = fileName.substring(fileName.indexOf(".")).toLowerCase();

        if (fileType.indexOf(suffix) == -1) {
            return false;
        }
        return true;
    }


    //检查文件大小
    public static Boolean checkFileSize(byte[] bytes ,String fileSizeLimit){
        int fileSize = Integer.parseInt(fileSizeLimit);
        if (bytes.length > fileSize) {
            return false;
        }
        else
            return true;
    }

    //检查文件是否存在
    public static boolean existFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    public static void main(String args[]){
        System.out.println(Tools.dateToStr(new Date()));
    }

    public static String getAbsolutePath(String filepath) {
        String replacePath = filepath;
        if (FileUtil.system.contains("linux")) {
            replacePath = filepath.replace('\\', '/');
        }
        return UploadFilePathUrl+replacePath;
    }
}
